package com.example.forum.services.impl;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.dao.ArticleReplyMapper;
import com.example.forum.exception.ApplicationException;
import com.example.forum.model.ArticleReply;
import com.example.forum.services.IArticleReplyService;
import com.example.forum.services.IArticleService;
import com.example.forum.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class ArticleReplyServiceImpl implements IArticleReplyService {
    @Autowired
    private ArticleReplyMapper articleReplyMapper;
    @Autowired
    private IArticleService articleService;

    @Override
    public void create(ArticleReply articleReply) {
        if(null==articleReply || articleReply.getArticleId()==null
        || articleReply.getPostUserId()==null || StringUtil.isEmpty(articleReply.getContent())){
            log.warn("传入的回复信息为空!");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_REPLY_IS_NULL));
        }
        //设置回复信息的默认值
        articleReply.setReplyId(null);
        articleReply.setReplyUserId(null);
        articleReply.setLikeCount(0);
        articleReply.setState((byte) 0);
        articleReply.setDeleteState((byte) 0);
        Date date = new Date();
        articleReply.setCreateTime(date);
        articleReply.setUpdateTime(date);
        //写入数据库
        int row = articleReplyMapper.insertSelective(articleReply);
        if(row!=1){
            log.error("回复用户帖子失败!出现内部异常");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_REPLY));
        }
        articleService.addOneReplyCountById(articleReply.getArticleId());
        log.info("帖子回复成功");
    }

    @Override
    public List<ArticleReply> selectByArticleId(Long articleId) {
        if(null == articleId || articleId <= 0){
            log.info("传入的帖子id为空! articleId:{}",articleId);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //DAO
        return articleReplyMapper.selectByArticleId(articleId);
    }
}
